<?php

namespace App\Console\Commands;

use App\Http\Controllers\Open\XgController;
use App\Models\Administrator;
use App\Models\Content;
use App\Models\Dohespider\Posts;
use App\Models\Role;
use App\Services\Spider\WuzhuisoDrive;
use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class XirunPosts extends Command
{
    protected $signature = 'xirun:posts_article {site_id*}';

    protected $description = '向迅润cms目标站批量推送文章';

    /*
     *
     * 这个文件的推送已经作废了，换到另外一个项目内
     */
    protected $domains = [
        ['domain'=>'cjiaoshou.cn','catid'=>3,'func_catalogue'=>'news'],
        ['domain'=>'fellous.com.cn','catid'=>1,'func_catalogue'=>'news'],
        ['domain'=>'99czw.com','catid'=>2,'func_catalogue'=>'article'],
        ['domain'=>'jstdgj.org.cn','catid'=>6,'func_catalogue'=>'news'] ,
        ['domain'=>'shrekedu.com','catid'=>1,'func_catalogue'=>'news'],
        ['domain'=>'topqihuo.com','catid'=>6,'func_catalogue'=>'news'],
        ['domain'=>'wpos.net.cn','catid'=>6,'func_catalogue'=>'news'],
        ['domain'=>'zrsykj.com','catid'=>1,'func_catalogue'=>'news'],
        ['domain'=>'haomei518.com','catid'=>2,'func_catalogue'=>'article'],
        ['domain'=>'scjinhaifeng.com','catid'=>2,'func_catalogue'=>'article'],
    ];


    protected $protocol = 'http://';
    protected $tabname =  'zbp_pos';
    protected $postlimit = 200;    //一次推送的
    protected $tag = 'lala客户关于cjiaoshou.cn等域名站群';    //不要轻易改动，引起从大河传的最后ID会变


    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {

        $argument = $this->argument('site_id');
        $site_idx =  $argument[0];

        if (intval($site_idx)==0) {
            echo '传参错误!!!';
            return false;
        }
        $this->singlePost($site_idx-1);
        echo '\r\n\r\n执行完成!!!\r\n\r\n';
    }

//    public function BatchPost() {
//        $i = 1;
//        foreach ($this->domains as $domain=>$val) {
//            echo "No.{$i}  \r\n";
//            $catid = $val['catid'];
//            $queryRet = DB::table('sync_table_lastid')->where(['tag'=>$this->tag])->orderBy('lastID')->first();
//            $lastID = 0;
//            if ($queryRet) {
//                $lastID = $queryRet->lastID;
//            }
//            //从大河过来的数据
//            DB::enableQueryLog();
//            $lastID =0 ;
//
//
//            $data = DB::connection('DoHeSpider_Mysql')->table('zbp_post')->where('log_ID','>',$lastID)->orderBy('log_ID')->limit($this->postlimit)->get();
//
//
////dd( $data->toArray(),">>>>>>>>>>\r\n",count($data->toArray()));
//
//            $ii = 1;
//            foreach ($data as $k=>$v) {
//
//                if ($v && $v->log_Title   && $v->log_Content ) {
//                    echo '   >>>> '.$ii."  ";
//                    //
//                    $log_content = preg_replace('/<img [^>]*>/','',$v->log_Content);
//                    $postRet = $this->postArticle($domain,$val['func_catalogue'],['catid' => $catid, 'title' =>$v->log_Title , 'description' =>$log_content ]);
//                    if ($postRet==1) {
//                        echo "; 结果：推送回应，成功";
//                        //删除
////                        DB::connection('DoHeSpider_Mysql')->table('zbp_post')->where('log_ID','>',$lastID)->delete();
////                        $this->savelogs($domain, $v->log_ID);
//                    } else {
//                        echo "; 结果：推送回应，失败!!!\r\n";
//                    }
//                    echo "\r\n";
//                }
//                $ii ++;
//            }
//            $i = $i+1;
//        }
//
//    }

    public function singlePost($i) {
            set_time_limit(0);
            $wait = rand(2*60, 3*60);
            $domain =  $this->domains[$i]['domain'];
            $catid =$this->domains[$i]['catid'];
            $func_catalogue = $this->domains[$i]['func_catalogue'];

            $outmsg = "No.{$i}  \r\n";
            $outmsg .= " {domain:$domain} ";
            $queryRet = DB::table('sync_table_lastid')->where(['tag'=>$this->tag])->orderBy('lastID')->first();
            $lastID = 0;
            if ($queryRet) {
                $lastID = $queryRet->lastID;
            }
            $data = DB::connection('DoHeSpider_Mysql')->table('zbp_post')->where('log_ID','>',$lastID)->orderBy('log_ID')->limit($this->postlimit)->get();

            $ii = 1;
            foreach ($data as $k=>$v) {
                sleep($wait);
                if ($v && $v->log_Title   && $v->log_Content ) {
                    $outmsg .= " \r\n  >>>> {{$ii}} {log_ID:{$v->log_ID}}";
                    //
                    $log_content = preg_replace('/<img [^>]*>/','',$v->log_Content);
                    $postRet = $this->postArticle($domain,$func_catalogue,['catid' => $catid, 'title' =>$v->log_Title , 'description' =>$log_content ]);
                    if ($postRet==1) {
                        $outmsg .= "; 结果：推送回应，成功";
                        //删除
//                        DB::connection('DoHeSpider_Mysql')->table('zbp_post')->where('log_ID','>',$lastID)->delete();
                        $this->savelogs($domain, $v->log_ID);
                    } else {
                        $outmsg .= "; 结果：推送回应，失败!!!\r\n";
                    }
                    $outmsg .= "\r\n";
                    echo $outmsg;
                    save_log($outmsg,'xirunposts');
                }
                $ii ++;
            }

    }

    private function postArticle($domain,$directory,$data) {
        $url = $this->protocol ."{$domain}/index.php?s={$directory}&c=wm&m=push&__dg_flag=post";
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
        ));

        // 设置要发送的数据
        if (is_array($data)) {
            $data=http_build_query($data);
        }

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($curl);
        curl_close($curl);
        echo date("Y-m-d H:i:s").">>> 推送站点: {{$domain}} ";
        if (!$response) {
            save_log(['url'=>$url,'postdata'=>$data,'msg'=>'推送出错'],'xirunposts');
            echo " || !!! 推送出错 !!! ";
            return false;
        }
        $response = json_decode($response,true);

        return  ($response && isset($response['code'])  && $response['code']==1)?1:false;
    }

    private function savelogs($domain,$id) {
        $ret = DB::table('sync_table_logs')->insert(['domain'=>$domain,'tabname'=>$this->tabname,'table_id'=>$id,'created_at'=>date("Y-m-d H:i:s")]);

        if ($ret) {
            if (DB::table('sync_table_lastid')->where(['tag'=>$this->tag])->count()>0) {
                DB::table('sync_table_lastid')->where(['tag'=>$this->tag])->update(['lastID' => $id, 'created_at' => date("Y-m-d H:i:s")]);
            }else {
                DB::table('sync_table_lastid')->insert([ 'tag' => $this->tag,'lastID' => $id, 'created_at' => date("Y-m-d H:i:s")]);
            }
        }
    }




}
